<script setup lang="ts">
import {
  deleteMemberOrderAPI,
  getMemberOrderAPI,
  getPayMockAPI,
  getPayWxPayMiniPayAPI,
  putMemberOrderReceiptByIdAPI,
} from '@/services'
import { OrderState, orderStateList } from '@/services/constants'
import type { OrderItem, OrderListParams } from '@/types'
import { ref, onMounted } from 'vue'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

interface Props {
  orderState: number
}
const props = defineProps<Props>()
const queryParams: Required<OrderListParams> = {
  page: 1,
  pageSize: 5,
  orderState: props.orderState,
}
const orderList = ref<OrderItem[]>([])
// 数据是否加载中标记，用于防止上拉加载触发多次请求（节流优化）
const isLoading = ref(false)
// 数据是否加载完毕标记
const isFinish = ref(false)
// 组件是否已初始化
const isInit = ref(false)
// 获取订单列表
const getMemberOrderList = async () => {
  if (isLoading.value) return
  if (isFinish.value) {
    return uni.showToast({ icon: 'none', title: '没有更多数据' })
  }
  isLoading.value = true
  const res = await getMemberOrderAPI(queryParams)
  orderList.value.push(...res.result.items)
  isLoading.value = false
  if (queryParams.page < res.result.pages) {
    queryParams.page++
  } else {
    isFinish.value = true
  }
}
onMounted(async () => {
  uni.showLoading()
  await getMemberOrderList()
  isInit.value = true
  // uni.hideLoading()
})

// 是否刷新订单标记
const isRefresh = ref(false)
// 下拉刷新订单数据
const onRefresherrefresh = async () => {
  isRefresh.value = true
  queryParams.page = 1
  orderList.value = []
  isFinish.value = false
  await getMemberOrderList()
  isRefresh.value = false
}

/* 删除订单 */
const onOrderDelete = (id: string) => {
  uni.showModal({
    title: '提示',
    content: '是否确定删除该订单？',
    confirmColor: '#27BA9B',
    success: async (res) => {
      if (res.confirm) {
        // 仅在订单状态为待评价、已完成、已取消时，可删除订单
        await deleteMemberOrderAPI({ ids: [id] })
        // 删除成功之后，主动删除前台相应的订单
        const index = orderList.value.findIndex((v) => v.id === id)
        orderList.value.splice(index, 1)
        uni.showToast({ icon: 'success', title: '订单删除成功' })
      }
    },
  })
}

/* 支付订单 */
const onOrderPay = async (id: string) => {
  if (import.meta.env.DEV) {
    // 开发环境：模拟支付，修改订单状态为已支付
    await getPayMockAPI({ orderId: id })
  } else {
    // #ifdef MP-WEIXIN
    // 微信生产环境：获取支付参数 + 发起微信支付
    const res = await getPayWxPayMiniPayAPI({ orderId: id })
    await wx.requestPayment(res.result)
    // #endif

    // #ifdef H5 || APP-PLUS
    // H5端和App端未开通支付，一律使用模拟支付体验
    await getPayMockAPI({ orderId: id })
    // #endif
  }
  uni.showToast({ icon: 'success', title: '支付成功' })
  if (props.orderState === OrderState.DaiFuKuan) {
    // 待付款：主动删除前台相应的订单
    const index = orderList.value.findIndex((v) => v.id === id)
    orderList.value.splice(index, 1)
  } else {
    // 全部：主动更新前台的订单状态为待发货
    const order = orderList.value.find((v) => v.id === id)
    order!.orderState = OrderState.DaiFaHuo
  }
}

/* 确认收货 */
const onOrderConfirm = (id: string) => {
  uni.showModal({
    title: '提示',
    content: '为保障您的权益，请收到货并确认无误后，再确认收货',
    confirmColor: '#27BA9B',
    success: async (res) => {
      if (res.confirm) {
        await putMemberOrderReceiptByIdAPI(id)
        uni.showToast({ icon: 'success', title: '确认收货成功' })
        if (props.orderState === OrderState.DaiShouHuo) {
          // 待收货：主动删除前台相应的订单
          const index = orderList.value.findIndex((v) => v.id === id)
          orderList.value.splice(index, 1)
        } else {
          // 全部：主动更新前台的订单状态为待评价
          const order = orderList.value.find((v) => v.id === id)
          order!.orderState = OrderState.DaiPingJia
        }
      }
    },
  })
}
</script>

<template>
  <scroll-view
    class="orders"
    scroll-y
    enable-back-to-top
    refresher-enabled
    :refresher-triggered="isRefresh"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="getMemberOrderList"
  >
    <view class="card" v-for="order in orderList" :key="order.id">
      <!-- 订单信息 -->
      <view class="status">
        <text class="date">{{ order.createTime }}</text>
        <!-- 订单状态文字 -->
        <text>{{ orderStateList[order.orderState].text }}</text>
        <!-- 待评价/已完成/已取消状态：展示删除订单 -->
        <text
          v-if="
            [OrderState.DaiPingJia, OrderState.YiWanCheng, OrderState.YiQuXiao].includes(
              order.orderState,
            )
          "
          class="icon-delete"
          @tap="onOrderDelete(order.id)"
          >删除</text
        >
      </view>
      <!-- 商品信息 -->
      <navigator
        v-for="sku in order.skus"
        :key="sku.id"
        class="goods"
        hover-class="none"
        :url="`/pagesOrder/detail/detail?id=${order.id}`"
      >
        <view class="cover">
          <image class="image" mode="aspectFit" :src="sku.image" />
        </view>
        <view class="meta">
          <view class="name ellipsis-1">{{ sku.name }}</view>
          <view class="attrsText ellipsis">{{ sku.attrsText }}</view>
        </view>
      </navigator>
      <!-- 支付信息 -->
      <view class="payment">
        <text class="quantity">共{{ order.totalNum }}件商品</text>
        <text>实付</text>
        <text class="amount"> <text class="symbol">¥</text>{{ order.payMoney.toFixed(2) }}</text>
      </view>
      <!-- 订单操作按钮 -->
      <view class="action">
        <!-- 待付款状态：显示去支付按钮 -->
        <template v-if="order.orderState === OrderState.DaiFuKuan">
          <view class="button primary" @tap="onOrderPay(order.id)">去支付</view>
        </template>
        <template v-else>
          <navigator
            class="button secondary"
            hover-class="none"
            :url="`/pagesOrder/create/create?orderId=${order.id}`"
          >
            再次购买
          </navigator>
          <!-- 待收货状态：展示确认收货 -->
          <view
            v-if="order.orderState === OrderState.DaiShouHuo"
            class="button primary"
            @tap="onOrderConfirm(order.id)"
            >确认收货</view
          >
        </template>
      </view>
    </view>
    <!-- 底部提示文字 -->
    <view
      v-show="isInit"
      class="loading-text"
      :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }"
    >
      {{ isFinish ? '- 没有更多数据 -' : '正在加载...' }}
    </view>
  </scroll-view>
</template>

<style lang="scss">
/* 订单列表 */
.orders {
  .card {
    margin: 20rpx 20rpx 0;
    padding: 20rpx;
    min-height: 100rpx;
    background-color: #fff;
    border-radius: 10rpx;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  /* 订单信息 */
  .status {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15rpx;
    font-size: 28rpx;
    color: #999;

    .date {
      flex: 1;
      color: #666;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      margin-left: 10rpx;
      padding-left: 10rpx;
      line-height: 1;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  /* 商品信息 */
  .goods {
    display: flex;
    margin-bottom: 20rpx;

    .cover {
      position: relative;
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      overflow: hidden;

      .image {
        width: 170rpx;
        height: 170rpx;
      }
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      line-height: 1;
      background-color: rgba(0, 0, 0, 0.6);
      border-radius: 10rpx 0 0 0;
    }

    .meta {
      position: relative;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      // align-self: flex-start;
      position: absolute;
      top: 40rpx;
      left: 0;
      padding: 0 15rpx;
      font-size: 24rpx;
      color: #888;
      line-height: 1.6;
      border-radius: 4rpx;
      background-color: #f7f7f8;
    }

    .more {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  /* 支付信息 */
  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #999;
    text-align: right;
    line-height: 1;
    border-bottom: 1rpx solid #eee;

    .quantity {
      margin-right: 16rpx;
      font-size: 24rpx;
    }

    .amount {
      margin-left: 6rpx;
      color: #444;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  /* 订单操作按钮 */
  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      width: 180rpx;
      height: 60rpx;
      font-size: 26rpx;
      color: #444;
      border: 1rpx solid #ccc;
      border-radius: 60rpx;
    }

    .secondary {
      color: #27ba9b;
      border-color: #27ba9b;
    }

    .primary {
      color: #fff;
      background-color: #27ba9b;
    }
  }

  /* 底部提示文字 */
  .loading-text {
    padding: 20rpx 0;
    font-size: 28rpx;
    color: #666;
    text-align: center;
  }
}
</style>
